package edu.bkcloud08.portal.controllers;

import java.util.Locale;

import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.host.HostPool;
import org.opennebula.client.vm.VirtualMachine;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import edu.bkcloud08.portal.models.Machine;
import edu.bkcloud08.portal.models.Template;

/**
 * Handles requests for the application home page.
 */
@Controller
public class CreateController {

	public VirtualMachine vm;

	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String index(Locale locale, Model model) {
		System.out.println("okie create");

		return set(new Machine(), locale, model);
	}

	@RequestMapping(value = "/create/set", method = RequestMethod.GET)
	public String set(Machine machine, Locale locale, Model model) {
		System.out.println("okie create set");

		return "create/set";
	}

	@RequestMapping(value = "create/runVM", method = RequestMethod.POST)
	@ModelAttribute("machine")
	public Machine runVM(Machine machine, Locale locale, Model model) {
		System.out.println("runVM ok");
		System.out.print("Trying to deploy the new VM... ");
		if (vm != null) {
			OneResponse rc;
			rc = vm.deploy(4); // 4 is the host id

			if (rc.isError()) {
				System.out.println("failed!");
			} else
				System.out.println("ok.");

		}
		machine = null;
		return machine;
	}

	@RequestMapping(value = "create/setVM", method = RequestMethod.POST)
	@ModelAttribute("machine")
	public Machine setVM(Machine machine, Locale locale, Model model) {
		System.out.println("set VM");
		System.out.println("ram = " + machine.getRam());
		System.out.println("cpu = " + machine.getCpu());
		System.out.println("hdd = " + machine.getHdd());

		try {
			Client oneClient = new Client();

			
			String vmTemplate = "NAME   = ttylinux_java\n"
					+ "CPU    = "
					+ machine.getCpu()
					+ "\n"
					+ "MEMORY = "
					+ machine.getRam()
					+ "\n\n"
					+ "DISK   = [ IMAGE = \"ttylinux\" ]\n"
					+ "NIC    = [ NETWORK_ID = 3 ]\n"

					+ "FEATURES=[ acpi=\"no\" ]\n"

					+ "CONTEXT = ["
					+ "hostname    = \"hqbk\",\n"
					+ "files      = \"/srv/cloud/one-templates/init.sh /home/oneadmin/.ssh/id_rsa.pub\",\n"
					+ "target      = \"hdc\",\n"
					+ "username    = \"oneadmin\",\n"
					+ "user_pubkey = \"/home/oneadmin/.ssh/id_rsa.pub\"\n"
					+ "]";

			// You can try to uncomment the NIC line, in that case OpenNebula
			// won't be able to insert this machine in the database.

			System.out.println("Virtual Machine Template:\n" + vmTemplate);
			System.out.println();

			System.out.print("Trying to allocate the virtual machine... ");
			OneResponse rc = VirtualMachine.allocate(oneClient, vmTemplate);

			if (rc.isError()) {
				System.out.println("failed!");
				throw new Exception(rc.getErrorMessage());
			}

			// The response message is the new VM's ID
			int newVMID = Integer.parseInt(rc.getMessage());
			System.out.println("ok, ID " + newVMID + ".");

			// We can create a representation for the new VM, using the returned
			// VM-ID
			vm = new VirtualMachine(newVMID, oneClient);

			// Let's hold the VM, so the scheduler won't try to deploy it
			System.out.print("Trying to hold the new VM... ");
			rc = vm.hold();

			if (rc.isError()) {
				System.out.println("failed!");
				throw new Exception(rc.getErrorMessage());
			} else
				System.out.println("ok.");

			System.out.print("Trying to release the new VM... ");
			rc = vm.release();

			if (rc.isError()) {
				System.out.println("failed!");
				throw new Exception(rc.getErrorMessage());
			} else
				System.out.println("ok.");

			// System.out.print("Trying to deploy the new VM... ");
			// rc = vm.deploy(4); // 4 is the host id
			//
			// if (rc.isError()) {
			// System.out.println("failed!");
			// throw new Exception(rc.getErrorMessage());
			// } else
			// System.out.println("ok.");

			// And now we can request its information.
			rc = vm.info();
			// HostPool hostpool = new HostPool(oneClient) ;
			// int numhosts = hostpool.getLength() ;

			if (rc.isError())
				throw new Exception(rc.getErrorMessage());

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		return machine;
	}

	@RequestMapping(value = "/create/choose", method = RequestMethod.GET)
	public String choose(Template template, Locale locale, Model model) {
		System.out.println("okie create choose");

		return "create/choose";
	}
}
